import React, { Component } from 'react';
import styled from 'styled-components';

import { Viewer, Ion, SceneMode, CircleEmitter, ParticleSystem, Transforms, Color, Cartesian3, Math } from 'cesium';
import 'cesium/Build/Cesium/Widgets/widgets.css';
// const FFT = require('fft.js');
import FFT from 'fft.js';
// Cesium容器的样式
const CesiumContainer = styled.div`
  width: 100%;
  height: 100vh; /* 使地图全屏显示 */
`;

class SimpleCesiumMap extends Component {
  cesiumContainerRef = React.createRef<HTMLDivElement>();
  viewer: Viewer | null = null;
  particleSystem: ParticleSystem | null = null;

  componentDidMount() {
    Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJhZGUzZjNiOC1lMWNmLTRmM2UtYTExNS0xNTllNmIxNzVmYjMiLCJpZCI6MjUzNTkwLCJpYXQiOjE3MzA5ODI4NDV9.HiyrHUyPFOPQ_TvDDuU3SZgordkdK010WzuNMQpYDyY';

    // 初始化 Cesium Viewer 实例
    this.viewer = new Viewer(this.cesiumContainerRef.current!, {
      scene3DOnly: false,
      selectionIndicator: true,
      baseLayerPicker: true,
      sceneMode: SceneMode.SCENE3D,
    });
    const f = new FFT(4096);

    const input = new Array(4096);
    input.fill(0);
    
    const out = f.createComplexArray();
    console.log(out)
    // 设置洪水泛滥的起始位置和模型矩阵
    const floodOrigin = Cartesian3.fromDegrees(-75.59777, 40.03883, 0);
    const modelMatrix = Transforms.eastNorthUpToFixedFrame(floodOrigin);

    // 创建粒子系统并添加到场景中
    this.particleSystem = new ParticleSystem({
      modelMatrix: modelMatrix,
      minimumSpeed: 1.0,
      maximumSpeed: 3.0,
      lifetime: 5.0,
      emitter: new CircleEmitter(1000.0),
      startScale: 1.0,
      endScale: 4.0,
      startColor: Color.BLUE.withAlpha(0.7),
      endColor: Color.BLUE.withAlpha(0.1),
      image: 'path/to/water_particle.png', // 替换为实际粒子图片路径
      emissionRate: 1000,
      bursts: [
        {
          time: 0.0,
          minimum: 50,
          maximum: 100,
          complete: false,
        },
      ],
      sizeInMeters: true,
    });

    this.viewer.scene.primitives.add(this.particleSystem);

    // 设置摄像机视角
    this.viewer.camera.flyTo({
      destination: Cartesian3.fromDegrees(-75.59777, 40.03883, 5000.0),
      orientation: {
        heading: Math.toRadians(0.0),
        pitch: Math.toRadians(-30.0),
        roll: 0.0,
      },
    });
  }

  componentWillUnmount() {
    try {
      // 销毁粒子系统和 Viewer 实例前检查是否存在
      if (this.particleSystem && this.viewer) {
        // 从场景中移除粒子系统，并销毁
        this.viewer.scene.primitives.remove(this.particleSystem);
        this.particleSystem.destroy();
        this.particleSystem = null;
      }

      // 销毁 Viewer 实例
      if (this.viewer) {
        this.viewer.destroy();
        this.viewer = null;
      }
    } catch (error) {
      console.error("Error during component unmounting and resource cleanup:", error);
    }
  }

  render() {
    return <CesiumContainer ref={this.cesiumContainerRef} />;
  }
}

export default SimpleCesiumMap;
